package cn.cvs.service.sysUser;

import cn.cvs.dao.sysUser.SysUserMapper;
import cn.cvs.pojo.SysUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * service层捕获异常，进行事务处理
 * 事务处理：调用不同dao的多个方法，必须使用同一个connection（connection作为参数传递）
 * 事务完成之后，需要在service层进行connection的关闭，在dao层关闭（PreparedStatement和ResultSet对象）
 * @author Administrator
 *
 */
@Service
public class SysUserServiceImpl implements SysUserService {
	@Resource
	private SysUserMapper sysUserMapper;
	@Override
	public boolean add(SysUser sysUser) throws Exception {
		boolean flag = false;
		sysUser.setCreatedTime(new Date());
		if(sysUserMapper.add(sysUser) > 0)
			flag = true;
		return flag;
	}
	@Override
	public SysUser login(String account, String userPassword) throws Exception {
		SysUser sysUser = sysUserMapper.selectByAccount(account);
		//匹配密码
		if(null != sysUser){
			if(!sysUser.getPassword().equals(userPassword))
				sysUser = null;
		}
		return sysUser;
	}
	@Override
	public List<SysUser> getUserList(String realName, Integer roleId, Integer pageIndex, Integer pageSize) throws Exception {
		int pageBegin = (pageIndex-1)*pageSize;
		return sysUserMapper.selectList(realName, roleId, pageBegin, pageSize);
	}

	@Override
	public SysUser getUserById(Integer id) throws Exception {
		return sysUserMapper.selectById(id);
	}
	@Override
	public boolean update(SysUser sysUser) throws Exception {
		boolean flag = false;
		sysUser.setUpdatedTime(new Date());
		if(sysUserMapper.update(sysUser) > 0)
			flag = true;
		return flag;
	}
	@Override
	public boolean updatePwd(Integer id, String pwd) throws Exception {
		boolean flag = false;
		if(sysUserMapper.updatePwd(id, pwd) > 0)
			flag = true;
		return flag;
	}

	@Override
	public SysUser getByAccount(String account) throws Exception {
		return sysUserMapper.selectByAccount(account);
	}

	@Override
	public boolean deleteById(Integer id) throws Exception {
		boolean flag = true;
		//先删除该条记录的上传附件
		SysUser sysUser = sysUserMapper.selectById(id);
		if(sysUser.getIdPicPath() != null && ! sysUser.getIdPicPath().equals("")){
			//删除服务器上个人证件照
			File file = new File(sysUser.getIdPicPath());
			if(file.exists()){
				flag = file.delete();
			}
		}
		if(flag && sysUser.getWorkPicPath() != null && !sysUser.getWorkPicPath().equals("")){
			//删除服务器上个人工作证照片
			File file = new File(sysUser.getWorkPicPath());
			if(file.exists()){
				flag = file.delete();
			}
		}
		if(flag){
			if(sysUserMapper.deleteById(id) < 1)
				flag = false;
		}
		return flag;
	}

	@Override
	public int getUserCount(String realName, Integer roleId) throws Exception {
		return sysUserMapper.selectCount(realName, roleId);
	}


}
